<template>
  <div class="task-create">
    <page-header
      title="创建任务"
      description="填写任务的基本信息，开始创建任务。媒介类型可以选择工作流或者脚本文件。"
    >
    </page-header>

    <div class="content-wrapper">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="task-form"
        status-icon
      >
        <div class="form-grid">
          <!-- 基本信息卡片 -->
          <div class="form-card">
            <div class="card-header">
              <el-icon><InfoFilled /></el-icon>
              <h3>基本信息</h3>
            </div>
            <el-form-item label="任务名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入任务名称" />
            </el-form-item>
            <el-form-item label="任务描述" prop="description">
              <el-input
                v-model="form.description"
                type="textarea"
                :rows="3"
                placeholder="请输入任务描述"
              />
            </el-form-item>
            <el-form-item label="执行类型" prop="execType">
              <el-radio-group v-model="form.execType">
                <el-radio-button label="立即执行">立即执行</el-radio-button>
                <el-radio-button label="周期执行">周期执行</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </div>

          <!-- 执行配置卡片 -->
          <div class="form-card">
            <div class="card-header">
              <el-icon><Setting /></el-icon>
              <h3>执行配置</h3>
            </div>
            <el-form-item label="执行主机" prop="execHost">
              <el-select
                v-model="selectedHosts"
                multiple
                filterable
                placeholder="请选择执行主机"
                @change="handleHostsChange"
              >
                <el-option
                  v-for="server in servers"
                  :key="server.id"
                  :label="server.hostname"
                  :value="server.hostname"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="执行用户" prop="execUser">
              <el-input v-model="form.execUser" placeholder="请输入执行用户" />
            </el-form-item>
          </div>

          <!-- 任务媒介卡片 -->
          <div class="form-card">
            <div class="card-header">
              <el-icon><Connection /></el-icon>
              <h3>任务媒介</h3>
            </div>
            <el-form-item label="媒介类型" prop="mediaType">
              <el-radio-group v-model="form.mediaType">
                <el-radio-button label="workflow">工作流</el-radio-button>
                <el-radio-button label="script">脚本</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="选择媒介" prop="mediaId">
              <el-select
                v-model="form.mediaId"
                filterable
                placeholder="请选择媒介"
                @change="handleMediaChange"
                :disabled="!form.mediaType"
              >
                <el-option
                  v-for="item in mediaOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <!-- 工作流跳过脚本选择 -->
            <el-form-item v-if="form.mediaType === 'workflow' && currentWorkflow" label="跳过脚本">
              <el-select
                v-model="form.skipped"
                multiple
                filterable
                placeholder="选择要跳过的脚本（可选）"
              >
                <el-option
                  v-for="script in workflowScripts"
                  :key="script"
                  :label="script"
                  :value="script"
                />
              </el-select>
            </el-form-item>
          </div>
        </div>

        <!-- 表单操作按钮 -->
        <div class="form-actions">
          <el-button @click="router.back()">取消</el-button>
          <el-button type="primary" :loading="loading" @click="handleSubmit">创建任务</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import PageHeader from '@/components/common/PageHeader.vue'
import { taskService } from '@/api/taskService'
import { assetService } from '@/api/assetService'
import type { Workflow, Script, ServerInfo } from '@/api/types'
import { useRoomConfigStore } from '@/store/roomConfigStore'
import { InfoFilled, Setting, Connection } from '@element-plus/icons-vue'

const router = useRouter()
const formRef = ref<FormInstance>()
const loading = ref(false)
const currentWorkflow = ref<Workflow | null>(null)
const roomConfigStore = useRoomConfigStore()
const servers = ref<ServerInfo[]>([])
const scripts = ref<Script[]>([])
const workflows = ref<Workflow[]>([])

// 表单数据
const form = ref({
  name: '',
  description: '',
  execType: '立即执行',
  execHost: '',
  execUser: 'root',
  mediaType: '',
  mediaId: undefined,
  workOrderId: '',
  skipped: [] as string[],
})

// 选中的主机列表
const selectedHosts = ref<string[]>([])

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
  description: [{ required: true, message: '请输入任务描述', trigger: 'blur' }],
  execHost: [{ required: true, message: '请选择执行主机', trigger: 'change' }],
  execUser: [{ required: true, message: '请输入执行用户', trigger: 'blur' }],
  mediaType: [{ required: true, message: '请选择媒介类型', trigger: 'change' }],
  mediaId: [{ required: true, message: '请选择媒介', trigger: 'change' }],
}

// 媒介选项
const mediaOptions = computed(() => {
  if (!form.value.mediaType) return []

  if (form.value.mediaType === 'workflow') {
    return workflows.value
  } else if (form.value.mediaType === 'script') {
    return scripts.value
  }
  return []
})

// 工作流脚本列表
const workflowScripts = computed(() => {
  if (!currentWorkflow.value) return []
  return currentWorkflow.value.chapters.flatMap((chapter) => chapter.tags.map((tag) => tag.name))
})

// 处理主机选择变化
const handleHostsChange = (hosts: string[]) => {
  form.value.execHost = hosts.join(',')
}

// 监听媒介类型变化
watch(
  () => form.value.mediaType,
  () => {
    form.value.mediaId = undefined
    currentWorkflow.value = null
    form.value.skipped = []
  },
)

// 加载服务器列表
const loadServers = async () => {
  if (!roomConfigStore.currentRoom) {
    ElMessage.warning('请先配置机房')
    return
  }

  try {
    const response = await assetService.getServersByRoom(roomConfigStore.currentRoom.room_id, {
      page: 1,
      page_size: 1000,
    })
    servers.value = response.items
  } catch (err) {
    console.error('获取服务器列表失败:', err)
    ElMessage.error('获取服务器列表失败')
  }
}

// 加载脚本列表
const loadScripts = async () => {
  try {
    const response = await taskService.getScripts({
      page: 1,
      page_size: 1000,
    })
    scripts.value = response.items
  } catch (err) {
    console.error('获取脚本列表失败:', err)
    ElMessage.error('获取脚本列表失败')
  }
}

// 加载工作流列表
const loadWorkflows = async () => {
  try {
    const response = await taskService.getWorkflows({
      page: 1,
      page_size: 1000,
    })
    workflows.value = response.items
  } catch (err) {
    console.error('获取工作流列表失败:', err)
    ElMessage.error('获取工作流列表失败')
  }
}

// 处理媒介选择变化
const handleMediaChange = async (id: number) => {
  if (!form.value.mediaType) return

  if (form.value.mediaType === 'workflow') {
    try {
      const workflow = await taskService.getWorkflowById(id)
      currentWorkflow.value = workflow
    } catch (err) {
      console.error('获取工作流详情失败:', err)
      ElMessage.error('获取工作流详情失败')
      form.value.mediaId = undefined
    }
  } else {
    currentWorkflow.value = null
    form.value.skipped = []
  }
}

// 初始化数据
onMounted(async () => {
  await Promise.all([loadServers(), loadScripts(), loadWorkflows()])
})

// 生成工单号
const generateWorkOrderId = () => {
  const date = new Date()
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const random = Math.floor(Math.random() * 1000)
    .toString()
    .padStart(3, '0')
  return `WO-${year}${month}${random}`
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    loading.value = true
    form.value.workOrderId = generateWorkOrderId()

    await taskService.createTask(form.value)
    ElMessage.success('创建成功')
    router.back()
  } catch (err) {
    console.error('创建任务失败:', err)
    ElMessage.error('创建失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped lang="scss">
.task-create {
  height: 100%;

  .content-wrapper {
    max-width: 1200px;
    margin: 0 auto;
    padding: 24px;
  }

  .form-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 24px;
    margin-bottom: 24px;
  }

  .form-card {
    padding: 24px;
    background: var(--el-bg-color);
    border-radius: 8px;
    box-shadow: var(--el-box-shadow-light);
    transition: all 0.3s;
    height: fit-content;

    &:hover {
      transform: translateY(-2px);
      box-shadow: var(--el-box-shadow);
    }

    .card-header {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 24px;
      padding-bottom: 16px;
      border-bottom: 1px solid var(--el-border-color-lighter);

      .el-icon {
        font-size: 20px;
        color: var(--el-color-primary);
      }

      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 500;
        color: var(--el-text-color-primary);
      }
    }

    :deep(.el-form-item:last-child) {
      margin-bottom: 0;
    }
  }

  .form-actions {
    display: flex;
    justify-content: center;
    gap: 12px;
    padding: 24px;
    background: var(--el-bg-color);
    border-radius: 8px;
    box-shadow: var(--el-box-shadow-light);

    .el-button {
      min-width: 120px;
    }
  }

  :deep(.el-select) {
    width: 100%;
  }
}
</style>
